<template>
  <el-dialog
    v-model="visible"
    title="添加新成员"
    width="600px"
    :draggable="true"
    class="add-member-dialog"
  >
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户姓名或手机号"
        clearable
        class="search-input"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-loading="loading">
      <el-scrollbar max-height="300px">
        <div v-if="searchResults.length > 0">
          <div
            v-for="user in searchResults"
            :key="user.id"
            class="user-item"
            :class="{
              'selected': selectedUser?.id === user.id,
              'disabled': isAlreadyMember(user)
            }"
            @click="handleUserClick(user)"
          >
            <!-- 用户信息 -->
            <el-avatar :size="40" :src="user.avatar" class="user-avatar">
              {{ user.name.charAt(0) }}
            </el-avatar>
            <div class="user-info">
              <div class="user-name">{{ user.name }}</div>
              <div class="user-phone">{{ user.phone }}</div>
            </div>

            <!-- 状态图标 -->
            <el-icon
              v-if="selectedUser?.id === user.id"
              class="check-icon"
              title="已选中"
            >
              <CircleCheck/>
            </el-icon>
            <el-icon
              v-else-if="isAlreadyMember(user)"
              class="error-icon"
              title="该用户已在家庭中"
            >
              <CircleClose/>
            </el-icon>
          </div>
        </div>
        <div v-else class="empty-state">
          <el-icon>
            <Search/>
          </el-icon>
          <p>
            {{
              searchQuery ?
                (members.length > 0 ? '未找到新用户或所有匹配用户已在家庭中' : '未找到匹配用户')
                : '输入关键词搜索用户'
            }}
          </p>
        </div>
      </el-scrollbar>
    </div>

    <!-- 角色选择 -->
    <div class="role-selector" v-if="selectedUser && searchResults.length > 0">
      <el-form-item label="分配角色">
        <el-select
          v-model="selectedRole"
          placeholder="请选择角色"
          style="width: 100%"
        >
          <el-option
            v-for="role in roleList"
            :key="role.code"
            :label="role.desc"
            :value="role.code"
          />
        </el-select>
      </el-form-item>
    </div>

    <!-- 对话框底部按钮 -->
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        @click="confirmAddMember"
        :disabled="!selectedUser || !currentFamilyId"
      >
        确认添加
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, computed} from "vue";
import {Search, CircleCheck, CircleClose} from '@element-plus/icons-vue';
import {ElMessage} from "element-plus";
import {searchMember, addMemberToFamily} from "@/api/member";
import type {Member, MemberForm} from "@/api/member/type.ts";

const props = defineProps({
  visible: Boolean,
  members: {
    type: Array as () => Member[],
    required: true
  },
  currentFamilyId: {
    type: Number,
    required: true
  }
});

const emit = defineEmits(['update:visible', 'refresh-member']);

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

const searchQuery = ref('');
const searchResults = ref<MemberForm[]>([]);
const selectedUser = ref<Member | null>(null);
const selectedRole = ref('USER');
const loading = ref(false);

// 检查用户是否已是成员
const isAlreadyMember = (user: Member) => {
  return props.members.some(member => member.id === user.id);
};

// 处理用户点击
const handleUserClick = (user: Member) => {
  if (isAlreadyMember(user)) {
    ElMessage.warning('该用户已是家庭成员，不可重复添加');
    return;
  }
  selectedUser.value = user;
};

// 搜索用户
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    searchResults.value = [];
    return;
  }
  loading.value = true;
  try {
    const res = await searchMember(searchQuery.value);
    if (res.code === "M000") {
      searchResults.value = res.data
    }
  } catch (error) {
    console.error('搜索失败:', error);
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
};

// 确认添加成员
const confirmAddMember = async () => {
  if (!selectedUser.value || !props.currentFamilyId) {
    ElMessage.warning('请选择成员或家庭ID无效');
    return;
  }

  try {
    const addMember = {
      userId: selectedUser.value.id!,
      familyId: props.currentFamilyId!,
      role: selectedRole.value!
    }
    const res = await addMemberToFamily(addMember);

    if (res.code === "M000") {
      emit('refresh-member');
      resetDialog();
      visible.value = false;
      ElMessage.success('添加成功');
    }
  } catch (error) {
    ElMessage.error('添加成员失败');
    console.error(error);
  }
};

// 重置对话框
const resetDialog = () => {
  searchQuery.value = '';
  searchResults.value = [];
  selectedUser.value = null;
  selectedRole.value = 'USER';
};

// 角色列表（示例）
const roleList = [
  {code: 'ADMIN', desc: '管理员'},
  {code: 'USER', desc: '普通成员'}
];
</script>


<style scoped lang="scss">
.add-member-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-dialog__header) {
    padding: 20px;
    margin-right: 0;
    background: linear-gradient(to right, #f6f7f9, #ffffff);
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .search-section {
    margin-bottom: 20px;

    .search-input {
      :deep(.el-input__wrapper) {
        border-radius: 8px;
        padding: 10px 15px;
        transition: all 0.3s;

        &:hover {
          border-color: #c0c4cc;
        }

        &:focus {
          border-color: #1F63FF;
          box-shadow: 0 0 0 2px rgba(31, 99, 255, 0.1);
        }
      }
    }
  }

  .search-results {
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    min-height: 200px;
    margin-bottom: 20px;

    .user-item {
      display: flex;
      align-items: center;
      padding: 12px 15px;
      cursor: pointer;
      transition: all 0.2s;
      position: relative;
      border-bottom: 1px solid #f5f5f5;

      &:hover {
        background-color: #f9f9f9;
      }

      &.selected {
        background-color: #f0f7ff;
      }

      &.disabled {
        cursor: not-allowed;
        opacity: 0.6;
        background-color: #f5f5f5 !important;

        &:hover {
          background-color: #f5f5f5 !important;
        }
      }

      .user-avatar {
        margin-right: 12px;
        background-color: #1F63FF;
        color: white;
      }

      .user-info {
        flex: 1;

        .user-name {
          font-weight: 500;
          margin-bottom: 4px;
        }

        .user-phone {
          font-size: 12px;
          color: #909399;
        }
      }

      .check-icon {
        color: #1F63FF;
        font-size: 18px;
      }

      .error-icon {
        color: #F56C6C;
        font-size: 18px;
      }

      .add-icon {
        color: #67C23A;
        font-size: 18px;
      }
    }

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 200px;
      color: #909399;

      .el-icon {
        font-size: 40px;
        margin-bottom: 15px;
      }

      p {
        margin: 0;
        font-size: 14px;
      }
    }
  }

  .role-selector {
    margin-top: 15px;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #555;
      margin-bottom: 8px;
    }

    :deep(.el-select__wrapper) {
      border-radius: 8px;
      padding: 10px 15px;
    }
  }

  :deep(.el-dialog__footer) {
    padding: 15px 20px;
    border-top: 1px solid #f0f0f0;
    text-align: right;

    .el-button {
      padding: 10px 20px;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s;

      &:first-child {
        &:hover {
          color: #1F63FF;
          border-color: #c6e2ff;
          background-color: #ecf5ff;
        }
      }

      &:last-child {
        background-color: #1F63FF;
        border-color: #1F63FF;

        &:hover {
          background-color: #3a7afe;
          box-shadow: 0 4px 12px rgba(31, 99, 255, 0.3);
        }

        &:disabled {
          background-color: #a0c0ff;
          border-color: #a0c0ff;
          cursor: not-allowed;
        }
      }
    }
  }
}
</style>
